<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 收银台
// +----------------------------------------------------------------------
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\Log;

class Cashier extends Common
{
    public function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        $domain = request()->domain();
        $cashier = Db::name('cashier')->where('aid',aid)->where('bid', bid)->find();
        if (empty($cashier)) {
            Db::name('cashier')->insert(['createtime' => time(), 'bid' => bid, 'aid' => aid, 'name' => '收银台']);
            $cashier = Db::name('cashier')->where('bid', bid)->find();
        }
        $cashier_url = $domain . '/cashier/index.html#/index/index?id=' . $cashier['id'];
        View::assign('info',$cashier);
        View::assign('cashier_url', $cashier_url);
        return View::fetch();
    }
    public function save(){
        $info = input('post.info/a');
        if($info['id']){
            $info['updatetime'] = time();
            Db::name('cashier')->where('aid',aid)->where('id',$info['id'])->update($info);
            \app\common\System::plog('编辑收银台'.$info['id']);
        }else{
            $info['aid'] = aid;
            $info['createtime'] = time();
            $id = Db::name('cashier')->insertGetId($info);
            \app\common\System::plog('添加收银台'.$id);
        }
        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);
    }


    public function cashier()
    {
        echo 'cashier html......';
//        return View::fetch();
    }
    //------------------------------收银台页面接口-----------------------//

    /**
     * @description 商品一级分类
     */
    public function getCategoryList()
    {
        if (bid > 0) {
            $list = Db::name('shop_category2')->where('aid', aid)->where('bid', bid)->where('pid', 0)->where('status', 1)->order('sort desc,id')->select()->toArray();
        } else {
            $list = Db::name('shop_category')->where('aid', aid)->where('pid', 0)->where('status', 1)->order('sort desc,id')->select()->toArray();
        }
        if (empty($list)) $list = [];
        return $this->json(1, 'ok', $list);
    }

    public function getAllCids($pid = '')
    {
        if (!is_array($pid)) {
            $pid = [$pid];
        }
        $cids = $pids1 = $pids2 = $pids3 = [];
        if (bid > 0) {
            $pids1 = Db::name('shop_category2')->where('aid', aid)->where('bid', bid)->where('pid', 'in', $pid)->where('status', 1)->order('sort desc,id')->column('id');
            if ($pids1) {
                $pids2 = Db::name('shop_category')->where('aid', aid)->where('bid', bid)->where('pid', 'in', $pids1)->where('status', 1)->order('sort desc,id')->column('id');
                if ($pids2) {
                    $pids3 = Db::name('shop_category')->where('aid', aid)->where('bid', bid)->where('pid', 'in', $pids2)->where('status', 1)->order('sort desc,id')->column('id');
                }
            }
        } else {
            $pids1 = Db::name('shop_category')->where('aid', aid)->where('pid', 'in', $pid)->where('status', 1)->order('sort desc,id')->column('id');
            if ($pids1) {
                $pids2 = Db::name('shop_category')->where('aid', aid)->where('pid', 'in', $pids1)->where('status', 1)->order('sort desc,id')->column('id');
                if ($pids2) {
                    $pids3 = Db::name('shop_category')->where('aid', aid)->where('pid', 'in', $pids2)->where('status', 1)->order('sort desc,id')->column('id');
                }
            }
        }
        $cids = array_merge($pid, $pids1, $pids2, $pids3);
        return $cids;
    }

    //收银台配置项返回
    public function getCashierInfo(){
        $cashier_id = input('param.cashier_id/d', 0);
        $info = Db::name('cashier')->where('aid',aid)->where('bid',bid)->where('id',$cashier_id)->find();
        if(empty($info)){
            return $this->json(0,'收银台信息缺失');
        }
        if(empty($info['option_name'])){
            $info['option_name'] = $this->user['un'];
        }
        $webinfo = Db::name('sysset')->where(['name'=>'webinfo'])->value('value');
        if($info['bid']>0){
            $binfo = Db::name('business')->where('aid',aid)->where('id',$info['bid'])->field('logo,name')->find();
        }else{
            $binfo = Db::name('admin_set')->where('aid',aid)->field('logo,name')->find();
        }
        $webinfo = $webinfo?json_decode($webinfo,true):[];
        $info['ico'] = $webinfo['ico']??'';
        $info['bname'] = $binfo['name']??'';
        $info['blogo'] = $binfo['logo']??'';
        $info['color1'] = $info['color1'] ? $info['color1'] : '#2792FF';
        $info['color1rgb'] = $info['color1'] ? hex2rgb($info['color1']) : hex2rgb('#2792FF');
        return  $this->json(1,'ok',$info);
    }

    /**
     * @description 商品列表
     */
    public function getProductList()
    {
        $page = input('param.page/d', 1);
        $limit = input('param.limit/d', 10);
        $cid = input('param.cid/d', 0);
        $where = array();
        $where[] = ['p.aid', '=', aid];
        $where[] = ['p.bid', '=', bid];
        $where[] = ['p.status', '=', 1];//已上架的
        $where[] = ['p.ischecked', '=', 1];//已通过审核
        $where[] = ['p.sell_price', '>', 0];//测试用
        $where[] = ['p.douyin_product_id', '=', ''];
        if (input('param.name')) $where[] = ['p.name|p.procode|p.barcode|g.barcode', 'like', '%' . input('param.name') . '%'];

//        if (input('param.code')) $where[] = ['procode|barcode', 'like', '%' . input('param.code') . '%'];

        if ($cid) {
            //获取一级分类下面的所有子类
            $cids = $this->getAllCids($cid);
            if ($cids) {
                $where[] = ['p.cid', 'in', $cids];
            } else {
                //无分类内容
                $where[] = ['p.cid', '=', '-1'];
            }
        }
//        $count = 0 + Db::name('shop_product')->where($where)->count();
        $data = Db::name('shop_product')->alias('p')->join('shop_guige g','p.id=g.proid')->group('p.id')->field('p.*')->where($where)->page($page, $limit)->order('sort desc,id desc')->select()->toArray();
        $cdata = Db::name('shop_category')->where('aid', aid)->column('name', 'id');
        if (bid > 0) {
            $cdata2 = Db::name('shop_category2')->Field('id,name')->where('aid', aid)->where('bid', bid)->order('sort desc,id')->column('name', 'id');
        }
        if (empty($data)) $data = [];
        foreach ($data as $k => $v) {
            $v['cid'] = explode(',', $v['cid']);
            $data[$k]['cname'] = null;
            if ($v['cid']) {
                foreach ($v['cid'] as $cid) {
                    if ($data[$k]['cname'])
                        $data[$k]['cname'] .= ' ' . $cdata[$cid];
                    else
                        $data[$k]['cname'] .= $cdata[$cid];
                }
            }
            if ($v['bid'] > 0) {
                $v['cid2'] = explode(',', $v['cid2']);
                $data[$k]['cname2'] = null;
                if ($v['cid2']) {
                    foreach ($v['cid2'] as $cid) {
                        if ($data[$k]['cname2'])
                            $data[$k]['cname2'] .= ' ' . $cdata2[$cid];
                        else
                            $data[$k]['cname2'] .= $cdata2[$cid];
                    }
                }
                $data[$k]['bname'] = Db::name('business')->where('aid', aid)->where('id', $v['bid'])->value('name');
            } else {
                $data[$k]['cname2'] = '';
                $data[$k]['bname'] = '平台自营';
            }
            if ($v['status'] == 2) { //设置上架时间
                if (strtotime($v['start_time']) <= time() && strtotime($v['end_time']) >= time()) {
                    $data[$k]['status'] = 1;
                } else {
                    $data[$k]['status'] = 0;
                }
            }
            if ($v['status'] == 3) { //设置上架周期
                $start_time = strtotime(date('Y-m-d ' . $v['start_hours']));
                $end_time = strtotime(date('Y-m-d ' . $v['end_hours']));
                if (($start_time < $end_time && $start_time <= time() && $end_time >= time()) || ($start_time >= $end_time && ($start_time <= time() || $end_time >= time()))) {
                    $data[$k]['status'] = 1;
                } else {
                    $data[$k]['status'] = 0;
                }
            }
            if ($v['bid'] == -1) $data[$k]['sort'] = $v['sort'] - 1000000;
            $guige = Db::name('shop_guige')->where('proid', $v['id'])->select()->toArray();
            if (count($guige) > 1) {
                $data[$k]['guige_num'] = count($guige);
            } else {
                $data[$k]['guige_num'] = 1;
            }
            $data[$k]['guigelist'] = $guige ?? [];
        }
        return $this->json(1, 'ok', $data);
    }

    /**
     * @description 加入收银台
     */
    public function addToCashier()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $proid = input('param.proid', 0);
        $barcode = input('param.barcode', 0);
        $ggid = input('param.ggid/d', 0);
        $num = input('param.num/d', 1);
        $price = input('param.price', 0);
        if ($num < 0) {
            $num = 1;
        }
        //如果是扫码获得的条形码信息
        if($barcode){
            $shopguige = Db::name('shop_guige')->where('aid',aid)->where('barcode',$barcode)->find();
            if(empty($shopguige) || empty($shopguige['proid'])){
                return $this->json(0, '未查询到相关商品');
            }else{
                $proid = $shopguige['proid'];
                $shopproduct = Db::name('shop_product')->where('aid',aid)->where('bid',bid)->where('id',$proid)->find();
                if(empty($shopproduct)){
                    return $this->json(0, '未查询到相关商品');
                }
                $proid = $shopproduct['id'];
                $num = 1;
            }
        }
        if (empty($proid)) {
            return $this->json(0, '请选择商品');
        }
        $order = $this->getWaitOrder($cashier_id);
        $goodsinfo = [];
        if (empty($order)) {
            //重新生成订单编号
            $date = date('ymdHis');
            $rand = rand(100000, 999999);
            $ordernum = 'C' . $date . $rand;
            $orderid = 0;
            $data = [];
            $data['ordernum'] = $ordernum;
            $data['cashier_id'] = $cashier_id;
            $data['aid'] = aid;
            $data['bid'] = bid;
            $data['createtime'] = time();
            $data['status'] = 0;
            $orderid = Db::name('cashier_order')->insertGetId($data);
            $order = $data;
            $order['id'] = $orderid;
        } else {
            $ordernum = $order['ordernum'];
            $orderid = $order['id'];
        }
        $sql = '';
        //直接收款
        $guige = [];
        if ($proid == -99) {
            if (empty($price) || !is_numeric($price)) {
                return $this->json(0, '请输入收款金额');
            }
            $goodsCount = Db::name('cashier_order_goods')->where('orderid', $orderid)->where('protype', 2)->count();
            $dbproid = $ordernum . '_' . ($goodsCount + 1);
            $product['id'] = $dbproid;
            $product['name'] = '直接收款';
            $product['sell_price'] = $price;
            $product['pic'] = '';
            $product['protype'] = 2;
        } else {
            //如果是多规格，需要指定规格
            $guiges = Db::name('shop_guige')->where('proid', $proid)->select()->toArray();
            if (count($guiges) > 1) {
                if (empty($ggid)) {
                    return $this->json(0, '请选择购买的商品规格');
                } else {
                    $guige = Db::name('shop_guige')->where('proid', $proid)->where('id', $ggid)->find();
                }
            } elseif (count($guiges) == 1) {
                $guige = $guiges[0];
                $ggid = $guige['id'];
            }
            $product = Db::name('shop_product')->where('aid', aid)->where('status', '<>', 0)->where('ischecked', 1)->where('id', $proid)->find();
            if (!$product) return $this->json(0, '产品不存在或已下架');
            $product['protype'] = 1;
            if($guige['stock']<1){
                return $this->json(0, '产品库存不足');
            }
        }
        if ($proid > 0) {
            $goodsinfo = Db::name('cashier_order_goods')->where('orderid', $order['id'])->where('proid', $proid)->where('ggid', $ggid)->find();
        }

        $goodsData = [];
        $goodsData['orderid'] = $orderid;
        $goodsData['proid'] = $product['id'];
        $goodsData['proname'] = $product['name'];
        $goodsData['ggid'] = $guige['id'] ?? 0;
        $goodsData['ggname'] = $guige['name'] ?? '';
        $goodsData['barcode'] = $guige['barcode'] ?? '';
        $goodsData['propic'] = $guige['pic'] ? $guige['pic'] : $product['pic'];
        $goodsData['sell_price'] = $guige['sell_price'] ? $guige['sell_price'] : $product['sell_price'];
        $goodsData['protype'] = $product['protype'];
        $goodsData['aid'] = aid;
        $goodsData['bid'] = bid;
        if (empty($goodsinfo)) {
            $goodsData['createtime'] = time();
            $goodsData['num'] = $num;
            Db::name('cashier_order_goods')->insert($goodsData);
        } else {
            $goodsData['num'] = $goodsinfo['num'] + $num;
            Db::name('cashier_order_goods')->where('id', $goodsinfo['id'])->update($goodsData);
        }
        return $this->json(1, 'ok');
    }

    /**
     * @description 挂单
     */
    public function hangup()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $mid = input('param.mid/d', 0);
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '暂无可挂订单');
        }
        $orderup = ['status' => 2, 'hangup_time' => time()];
        if($mid){
            $orderup['mid'] = $mid;
            Db::name('cashier_order_goods')->where('orderid', $order['id'])->update(['mid'=>$mid]);
        }
        Db::name('cashier_order')->where('id', $order['id'])->update($orderup);
        return $this->json(1, '挂单成功');
    }

    /**
     * @description 取单
     */
    public function cancelHangup()
    {
        $orderid = input('param.orderid/d', 0);
        $order = Db::name('cashier_order')->where('aid', aid)->where('bid', bid)->where('id', $orderid)->find();
        $order0 = $this->getWaitOrder($order['cashier_id']);

        if (empty($order)) {
            return $this->json(0, '无效订单');
        }
        if ($order0) {
            $goodsC = Db::name('cashier_order_goods')->where('orderid',$order0['id'])->count();
            if($goodsC<1){
                //如果待结算没有物品，则直接删除这个订单
                Db::name('cashier_order')->where('id',$order0['id'])->delete();
            }else{
                return $this->json(0, '请先结算其他订单后再取单');
            }
        }
        if ($order['status'] != 2) {
            return $this->json(0, '订单状态有误');
        }
        Db::name('cashier_order')->where('id', $order['id'])->update(['status' => 0]);
        return $this->json(1, '取单成功');
    }

    public function payPreview(){
        $cashier_id = input('param.cashier_id/d', 0);
        $couponrid = input('param.couponid/d', 0);
        $mid = input('param.mid/d', 0);
        $userscore = input('param.userscore/d', 0);
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '无待结算订单');
        }
        //优惠券
        $bid = bid;
        $userinfo = [];
        $newcouponlist = [];
        //计算总价
        $allgoods = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        if (empty($allgoods)) {
            return $this->json(0, '无待结算商品');
        }
        $member = [];
        //商城商品
        $totalprice = 0;
        $buydata = [];
        $proids = [];
        foreach ($allgoods as $k => $v) {
            $totalprice += $v['sell_price'] * $v['num'];
            //商城商品
            if ($v['protype'] == 1) {
                $buydata[] = $v;
                $proids[] = $v['proid'];
                //库存校验
                $gginfo = Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->find();
                if($gginfo['stock']<$v['num']){
                    return $this->json(0, $v['proname'].'('.$v['ggname'].')'.'库存不足');
                }
            }
        }
        $cids = [];
        if ($proids) {
            $cidarr = Db::name('shop_product')->where('aid',aid)->where('bid', bid)->where('id', 'in', $proids)->column('cid','id');
            if($cidarr){
                $cids = array_values($cidarr);
            }
        }
        if ($mid) {
            $member = Db::name('member')->where('id', $mid)->where('aid',aid)->find();
            $adminset = Db::name('admin_set')->where('aid', aid)->find();
            $userlevel = Db::name('member_level')->where('aid', aid)->where('id', $member['levelid'])->find();
            $level_discount = is_numeric($userlevel['discount'])?$userlevel['discount']:10;
            $userinfo['discount'] = $level_discount;
            $userinfo['score'] = $member['score'];
            $userinfo['score2money'] = $adminset['score2money'];
            $userinfo['dkmoney'] = round($userinfo['score'] * $userinfo['score2money'], 2);
            $userinfo['scoredkmaxpercent'] = $adminset['scoredkmaxpercent'];
            $userinfo['money'] = $member['money'];
            $couponlist = Db::name('coupon_record')
                ->where('aid', aid)->where('mid', $mid)->where('bid', $bid)->where('type', 1)->where('status', 0)->where('starttime', '<=', time())->where('endtime', '>', time())
                ->order('id desc')->select()->toArray();
            if (!$couponlist) $couponlist = [];
            foreach ($couponlist as $k => $v) {
                $couponinfo = Db::name('coupon')->where('aid', aid)->where('id', $v['couponid'])->find();
                if(empty($couponinfo)){
                    continue;
                }
                $gettj = explode(',', $couponinfo['gettj']);
                if (!in_array('-1', $gettj) && !in_array($member['levelid'], $gettj)) { //不是所有人
                    continue;
                }
                //0全场通用,1指定类目,2指定商品
                if (!in_array($couponinfo['fwtype'], [0, 1, 2])) {
                    continue;
                }
                if ($couponinfo['fwtype'] == 2) {//指定商品可用
                    $productids = explode(',', $couponinfo['productids']);
                    if (!array_intersect($proids, $productids)) {
                        continue;
                    }
                    $thistotalprice = 0;
                    foreach ($buydata as $k2 => $product) {
                        if (in_array($product['proid'],$productids)){
                            $thistotalprice += $product['sell_price'] * $product['num'];
                        }
                    }
                    if ($thistotalprice < $v['minprice']) {
                        continue;
                    }
                }
                if ($couponinfo['fwtype'] == 1) {//指定类目可用
                    $categoryids = explode(',', $couponinfo['categoryids']);
                    $categoryids1 = Db::name('shop_category')->where('pid', 'in', $categoryids)->column('id');
                    if (empty($categoryids1)) $categoryids1 = [];
                    $categoryids = array_merge($categoryids, $categoryids1);
                    if (!array_intersect($cids, $categoryids)) {
                        continue;
                    }
                    $thistotalprice = 0;
                    foreach ($buydata as $k2 => $product) {
                        if(isset($cidarr[$product['proid']])){
                            $thistotalprice += $product['sell_price'] * $product['num'];
                        }
                    }
                    if ($thistotalprice < $v['minprice']) {
                        continue;
                    }
                }
                if ($v['bid'] > 0) {
                    $binfo = Db::name('business')->where('aid', aid)->where('id', $v['bid'])->find();
                    $v['bname'] = $binfo['name'] ?? '';
                }
                $v['starttime'] = date('Y-m-d H:i:s',$v['starttime']);
                $v['endtime'] = date('Y-m-d H:i:s',$v['endtime']);
                $newcouponlist[] = $v;
            }
        }
        //抹零
        $return = [];
        $orderResult = $this->getOrderPrice($order,$couponrid,$userscore,$mid);
        if($orderResult['status']!=1){
            return $this->json(0, $orderResult['msg']);
        }
        $return['totalprice'] = round($orderResult['pre_totalprice'],2);
        $return['final_totalprice'] = round($orderResult['totalprice'],2);
        $return['leveldk_money'] = $orderResult['leveldk_money'];
        $return['coupon_money'] = $orderResult['coupon_money'];
        $return['scoredk_money'] = $orderResult['scoredk_money'];
        $return['moling_money'] = $orderResult['moling_money'];
        $return['totalscore'] = $orderResult['totalscore'];
        $set = Db::name('admin_set')->where('aid', aid)->find();
        $paylist[] = ['paytypeid'=>1,'name'=>'余额'];
        if($set['wxpay']){
            $paylist[] = ['paytypeid'=>2,'name'=>'微信'];
        }
        if($set['alipay']){
            $paylist[] = ['paytypeid'=>3,'name'=>'支付宝'];
        }
        $return['memberinfo'] = $userinfo??'';
        $return['couponlist'] = $newcouponlist;
        $return['paylist'] = $paylist;

        return $this->json(1,'ok',$return);
    }

    /**
     * @description 收银台结算
     *  type=1=>微信扫码支付
     *  type=2=>支付宝扫码支付
     *  type=3=>现金
     *  type=4=>余额支付
     */
    public function pay()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $couponrid = input('param.couponid/d', 0);
        $mid = input('param.mid/d', 0);
        $userscore = input('param.userscore/d', 0);
        $paytype = input('param.paytype/d', 0);
        if($paytype==1){
            return $this->wxScanPay($cashier_id,$mid,$couponrid,$userscore);
        }elseif($paytype==2){
            return $this->aliScanPay($cashier_id,$mid,$couponrid,$userscore);
        }elseif($paytype==3){
            return $this->cashPay($cashier_id,$mid,$couponrid,$userscore);
        }elseif($paytype==4){
            return $this->moneyPay($cashier_id,$mid,$couponrid,$userscore);
        }else{
            return $this->json(0,'非法请求');
        }
    }
    //扫码枪微信扫码支付
    protected function wxScanPay($cashier_id=0,$mid=0,$couponrid=0,$userscore=0){
        $auth_code = input('param.auth_code');
        //验证code是否正确
        $reg = '/^1[0-6][0-9]{16}$/';
        if(!preg_match($reg,$auth_code)){
            return $this->json(0, '无效的付款码');
        }
//        $file = ROOT_PATH.'runtime/log/wxpay.txt';
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '无待结算订单');
        }
        $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        if (empty($goodslist)) {
            return $this->json(0, '无待结算商品');
        }
        foreach ($goodslist as $k=>$v){
            if($v['protype']==1){
                //库存校验
                $gginfo = Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->find();
                if($gginfo['stock']<$v['num']){
                    return $this->json(0, $v['proname'].'('.$v['ggname'].')'.'库存不足');
                }
            }
        }
        $orderResult = $this->getOrderPrice($order,$couponrid,$userscore,$mid);
        if($orderResult['status']!=1){
            return $this->json(0, $orderResult['msg']);
        }
        $set = Db::name('admin_set')->where('aid',aid)->find();
        $wxpaymoney  = $orderResult['totalprice'];
        if($wxpaymoney > 0){
            if(in_array('mp',$this->platform)){
                $appinfo = \app\common\System::appinfo(aid,'mp');
            }else{
                $appinfo = \app\common\System::appinfo(aid,'wx');
            }
            $appid = $appinfo['appid'];
            $pars = [];
            if($appinfo['wxpay_type']==0){
                $pars['appid'] = $appid;
                $pars['mch_id'] = $appinfo['wxpay_mchid'];
                $mchkey = $appinfo['wxpay_mchkey'];
            }else{
                $dbwxpayset = Db::name('sysset')->where('name','wxpayset')->value('value');
                $dbwxpayset = json_decode($dbwxpayset,true);
                if(!$dbwxpayset){
                    return $this->json(0,'未配置服务商微信支付信息');
                }
                $pars['appid'] = $dbwxpayset['appid'];
                //$pars['sub_appid'] = $appid;
                $pars['mch_id'] = $dbwxpayset['mchid'];
                $pars['sub_mch_id'] = $appinfo['wxpay_sub_mchid'];
                $mchkey = $dbwxpayset['mchkey'];
            }
            $pars['body'] = $set['name'].'-付款码付款';
            $pars['out_trade_no'] = $order['ordernum'];
            $pars['total_fee'] = $wxpaymoney*100;
            $pars['spbill_create_ip'] = request()->ip();
            $pars['auth_code'] = $auth_code;
            $pars['nonce_str'] = random(8);
            ksort($pars, SORT_STRING);
            $string1 = '';
            foreach ($pars as $key => $v){
                if (empty($v)) {
                    continue;
                }
                $string1 .= "{$key}={$v}&";
            }
            $string1 .= "key=".$mchkey;
            $pars['sign'] = strtoupper(md5($string1));
            $dat = array2xml($pars);
            $response = request_post('https://api.mch.weixin.qq.com/pay/micropay', $dat);
            $response = @simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->wlog(json_encode($response));
            //直接支付成功
            if($response->return_code=='SUCCESS' && $response->result_code=='SUCCESS' && $response->trade_type=='MICROPAY'){
                $transaction_id = $response->transaction_id;
            }else{
                $result = false;
                for($i=0;$i<10;$i++){
                    $pars2          = array();
                    if($appinfo['wxpay_type']==0){
                        $pars2['appid'] = $appid;
                        $pars2['mch_id'] = $appinfo['wxpay_mchid'];
                        $mchkey = $appinfo['wxpay_mchkey'];
                    }else{
                        $dbwxpayset = Db::name('sysset')->where('name','wxpayset')->value('value');
                        $dbwxpayset = json_decode($dbwxpayset,true);
                        if(!$dbwxpayset){
                            return $this->json(0,'未配置服务商微信支付信息');
                        }
                        $pars2['appid'] = $dbwxpayset['appid'];
                        $pars2['mch_id'] = $dbwxpayset['mchid'];
                        $pars2['sub_mch_id'] = $appinfo['wxpay_sub_mchid'];
                        $mchkey = $dbwxpayset['mchkey'];
                    }
                    $pars2['out_trade_no'] = $order['ordernum'];
                    $pars2['nonce_str'] = random(8);
                    ksort($pars2, SORT_STRING);
                    $string2 = '';
                    foreach ($pars2 as $key => $v){
                        if (empty($v)) {
                            continue;
                        }
                        $string2 .= "{$key}={$v}&";
                    }
                    $string2 .= "key=".$mchkey;
                    $pars2['sign'] = strtoupper(md5($string2));
                    $dat2 = array2xml($pars2);
                    $response2 = request_post('https://api.mch.weixin.qq.com/pay/orderquery', $dat2);
                    $response2 = @simplexml_load_string($response2, 'SimpleXMLElement', LIBXML_NOCDATA);
                    //
                    $this->wlog('-----第'.$i.'次查询-------');
                    $this->wlog(json_encode($response2));
                    if($response2->return_code=='FAIL'){
                        return $this->json(0,'支付失败：'.strval($response2->return_msg));
                    }else{
                        if ($response2->return_code=='SUCCESS' && $response2->result_code == 'SUCCESS' && $response2->trade_state=="SUCCESS") {
                            $result = true;
                            $transaction_id = $response2->transaction_id;
                            break;
                        }elseif($response2->trade_state == 'PAYERROR'){
                            $this->refreshOrdernum($order['id']);
                            return $this->json(0,'支付失败：'.strval($response2->trade_state_desc));
                        }
                    }
                    sleep(3);
                }

            }

            if($transaction_id){
                $orderup= [];
                $orderup['status'] = 1;
                $orderup['paytype'] = '收银台微信扫码';
                $orderup['paytypeid'] = 2;
                $orderup['paynum'] = $transaction_id;
                $orderup['paytime'] = time();
                $orderup['pre_totalprice'] = $orderResult['pre_totalprice'];
                $orderup['totalprice'] = $orderResult['totalprice'];
                $orderup['moling_money'] = $orderResult['moling_money'];
                if($orderResult['coupon_money']>0){
                    $orderup['coupon_money'] = $orderResult['coupon_money'];
                    $orderup['coupon_rid'] = $couponrid;
                }
                $orderup['scoredk_money'] = $orderResult['scoredk_money'];
                $orderup['leveldk_money'] = $orderResult['leveldk_money'];
                $orderup['uid'] = $this->uid;
                $orderup['mid'] = $mid;
            }else{
                return $this->json(0,'支付失败');
            }
        }else{
            $orderup= [];
            $orderup['status'] = 1;
            $orderup['paytype'] = '无须支付';
            $orderup['paynum'] = '';
            $orderup['paytime'] = time();
            $orderup['pre_totalprice'] = $orderResult['pre_totalprice'];
            $orderup['totalprice'] = $orderResult['totalprice'];
            $orderup['moling_money'] = $orderResult['moling_money'];
            $orderup['coupon_money'] = $orderResult['coupon_money'];
            $orderup['scoredk_money'] = $orderResult['scoredk_money'];
            $orderup['leveldk_money'] = $orderResult['leveldk_money'];
            $orderup['uid'] = $this->uid;
            $orderup['mid'] = $mid;
        }
        $res = Db::name('cashier_order')->where('id',$order['id'])->update($orderup);
        if($res){
            //减库存
            foreach ($goodslist as $k=>$v){
                $num = $v['num'];
                Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num")]);
                Db::name('shop_product')->where('aid',aid)->where('id',$v['proid'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num")]);
            }
            \app\common\Wifiprint::print(aid,'cashier',$order['id']);
            $this->afterpay($order['id']);
            return $this->json(1,'支付成功');
        }else{
            return $this->json(0,'支付失败');
        }
    }

    protected function afterPay($orderid=0){
        $order = Db::name('cashier_order')->where('aid',aid)->where('id',$orderid)->find();
        if($order && $order['coupon_rid']){
            Db::name('coupon_record')->where('id',$order['coupon_rid'])->where('mid',$order['mid'])->update(['status'=>1,'usetime'=>time()]);
        }
    }
    protected function refreshOrdernum($orderid=''){
        $date = date('ymdHis');
        $rand = rand(100000, 999999);
        $newordernum = 'C' . $date . $rand;
        Db::name('cashier_order')->where('id',$orderid)->update(['ordernum'=>$newordernum]);
    }

    protected function wlog($content){
        return ;
        $file = ROOT_PATH.'runtime/log/wxpay.txt';
        file_put_contents($file,date('Y-m-d H:i:s').PHP_EOL,FILE_APPEND);
        file_put_contents($file,$content.PHP_EOL,FILE_APPEND);
    }

    //支付宝扫码支付
    protected function aliScanPay(){
        return $this->json(0,'该支付方式暂不支持');
    }

    //现金支付（线下其他支付方式，直接更改订单状态）
    protected function cashPay($cashier_id=0,$mid=0,$couponrid=0,$userscore=0){
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '无待结算订单');
        }
        $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        if (empty($goodslist)) {
            return $this->json(0, '无待结算商品');
        }
        $orderResult = $this->getOrderPrice($order,$couponrid,$userscore,$mid);
        if($orderResult['status']!=1){
            return $this->json(0, $orderResult['msg']);
        }
        //抹零
        $orderup = [];
        $orderup['pre_totalprice'] = $orderResult['pre_totalprice'];
        $orderup['totalprice'] = $orderResult['totalprice'];
        $orderup['moling_money'] = $orderResult['moling_money'];
        if($orderResult['coupon_money']>0){
            $orderup['coupon_money'] = $orderResult['coupon_money'];
            $orderup['coupon_rid'] = $couponrid;
        }
        $orderup['scoredk_money'] = $orderResult['scoredk_money'];
        $orderup['leveldk_money'] = $orderResult['leveldk_money'];
        $orderup['mid'] = $mid;
        $orderup['paytime'] = time();
        $orderup['paytype'] = '现金支付';
        $orderup['status'] = 1;
        Db::name('cashier_order')->where('bid', bid)->where('aid', aid)->where('id', $order['id'])->update($orderup);
        $this->afterPay($order['id']);
        \app\common\Wifiprint::print(aid,'cashier',$order['id']);
        return $this->json(1, '支付成功');
    }
    //余额支付
    protected function moneyPay($cashier_id=0,$mid=0,$couponrid=0,$userscore=0){
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '无待结算订单');
        }
        $scoredk_money = 0;
        //计算总价
        $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        if (empty($goodslist)) {
            return $this->json(0, '无待结算商品');
        }
        foreach ($goodslist as $k=>$v){
            if($v['protype']==1){
                //库存校验
                $gginfo = Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->find();
                if($gginfo['stock']<$v['num']){
                    return $this->json(0, $v['proname'].'('.$v['ggname'].')'.'库存不足');
                }
            }
        }
        if(empty($mid)){
            return $this->json(0, '余额支付请选择会员账号');
        }
        Db::startTrans();
        $member = Db::name('member')->where('id', $mid)->where('aid', aid)->lock(true)->find();
        if(empty($member)){
            Db::rollback();
            return $this->json(0,'会员信息有误');
        }
        $orderResult = $this->getOrderPrice($order,$couponrid,$userscore,$mid);
        if($orderResult['status']!=1){
            Db::rollback();
            return $this->json(0, $orderResult['msg']);
        }
        //抹零
        $orderup = [];
        $orderup['pre_totalprice'] = $orderResult['pre_totalprice'];
        $orderup['totalprice'] = $orderResult['totalprice'];
        $orderup['moling_money'] = $orderResult['moling_money'];
        if($orderResult['coupon_money']>0){
            $orderup['coupon_money'] = $orderResult['coupon_money'];
            $orderup['coupon_rid'] = $couponrid;
        }
        $orderup['scoredk_money'] = $orderResult['scoredk_money'];
        $orderup['leveldk_money'] = $orderResult['leveldk_money'];
        $orderup['mid'] = $mid;
        if($orderup['coupon_money']>0){
            Db::name('coupon_record')->where('id', $couponrid)->update(['status' => 1, 'usetime' => time()]);
        }
        $totalscore = $orderResult['totalscore'];
        Db::name('cashier_order')->where('id', $order['id'])->update($orderup);
        $payorderid = \app\model\Payorder::createorder(aid, $order['bid'], $mid, 'cashier', $order['id'], $order['ordernum'], '收银台买单', $orderup['totalprice'], $totalscore);

        if($member['money'] < $orderup['totalprice']){
            Db::rollback();
            return $this->json(0,t('余额').'不足,请充值');
        }
        if($orderup['totalprice'] > 0){
            //减去会员的余额
            \app\common\Member::addmoney(aid,$mid,-$orderup['totalprice'],'收银台买单,订单号: '.$order['ordernum']);
        }
        if($totalscore > 0){
            //减去会员的积分
            \app\common\Member::addscore(aid,$mid,-$totalscore,'收银台买单,订单号: '.$order['ordernum']);
        }
        $res = \app\model\Payorder::payorder($payorderid,t('余额').'支付',1,'');
        if($res && $res['status']==1){
            //减库存
            foreach ($goodslist as $k=>$v){
                $num = $v['num'];
                Db::name('shop_guige')->where('aid',aid)->where('id',$v['ggid'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num")]);
                Db::name('shop_product')->where('aid',aid)->where('id',$v['proid'])->update(['stock'=>Db::raw("stock-$num"),'sales'=>Db::raw("sales+$num")]);
            }
            Db::commit();
            $this->afterpay($order['id']);
            \app\common\Wifiprint::print(aid,'cashier',$order['id']);
            return $this->json(1,'付款成功');
        }else{
            Db::rollback();
            return $this->json(0,'付款失败');
        }
    }

    //待支付订单
    public function getWaitPayOrder()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $remove_zero = input('param.remove_zero/d', 0);
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(1, '无待结算订单', '');
        }
        $set = Db::name('cashier')->where('id', $cashier_id)->where('bid', bid)->find();
        if ($order['remove_zero'] != $remove_zero) {
            Db::name('cashier_order')->where('id', $order['id'])->update(['remove_zero' => $remove_zero, 'remove_zero_length' => $set['remove_zero_length'] ?? 0]);
        }
        $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        //待结算订单，读取库存
        $discount_totalmoney = 0;
        $totalprice = 0;
        if (empty($goodslist)) $goodslist = [];
        foreach ($goodslist as $gk => $goods) {
            $stock = 0;
            if ($goods['protype'] == 1) {
                $stock = Db::name('shop_guige')->where('proid', $goods['proid'])->where('id', $goods['ggid'])->value('stock');
            }
            $gtotalprice = $goods['sell_price'] * $goods['num'];
            $goodslist[$gk]['totalprice'] = round($gtotalprice,2);
            $totalprice = $totalprice + $gtotalprice;
            $goodslist[$gk]['stock'] = $stock ?? 0;
        }
        $order['prolist'] = $goodslist ?? [];
        $order['remove_zero'] = $remove_zero;
        $order['remove_zero_length'] = $set['remove_zero_length'] ?? 0;
        if ($remove_zero == 1) {
            $zeroinfo = $this->removeZero($totalprice,$cashier_id);
            $order['totalprice'] = $zeroinfo['totalprice'];
            $order['discount_money'] = $zeroinfo['moling_money'];
        }else{
            $order['totalprice'] = round($totalprice - $discount_totalmoney, 2);
            $order['discount_money'] = $discount_totalmoney;
        }
        return $this->json(1, 'ok', $order);
    }
    //抹零
    protected function removeZero($totalprice,$cashier_id=0){
        if($cashier_id){
            $set = Db::name('cashier')->where('id', $cashier_id)->where('bid', bid)->find();
        }else{
            $set['remove_zero_length'] = 1;//抹去一位
        }
        $discount_totalmoney = 0;
        $zero_length = $set['remove_zero_length'];

        $totalprice = sprintf("%.2f", $totalprice);

        //小于100的 不支持整数部分抹零
        if ($totalprice < 100) {
            $zero_length = min(2, $zero_length);
        }
        if (strlen($totalprice) - 1 <= $zero_length) {
            $zero_length = 2;
        }
        if ($zero_length > 0 && $zero_length <= 2) {
            $discount = substr($totalprice, 0 - $zero_length);
            $discount_money = round($discount / 100, 2);
        } elseif ($zero_length > 2) {
            $discount_money = substr($totalprice, 0 - ($zero_length + 1));
        }
        $discount_totalmoney = round($discount_totalmoney + $discount_money,2);
        $totalprice = round($totalprice - $discount_totalmoney,2);
        return ['totalprice'=>$totalprice,'moling_money'=>$discount_totalmoney];
    }

    /**
     * 获取收银台订单信息
     * 待结算status=0
     * 已结算订单status=1
     * 挂单status=2
     */
    public function getCashierOrder()
    {
        $status = input('param.status/d', 1);
//        $bid = input('param.bid/d',0);
        $cashier_id = input('param.cashier_id/d', 0);
        $keyword = input('param.keyword', 0);
        $where = [];
        $where[] = ['o.aid','=',aid];
        $where[] = ['o.status' ,'=', $status];
        $where[] = ['o.bid','=',bid];
        $where[] = ['o.cashier_id','=',$cashier_id];
        if($keyword){
            $where[] = ['g.proname|g.barcode','like','%'.$keyword.'%'];
        }
        if($status==2){
            $orderby = 'hangup_time desc';
        }else{
            $orderby = 'id desc';
        }
        $lists = Db::name('cashier_order')->alias('o')->join('cashier_order_goods g','o.id=g.orderid')->group('o.id')->where($where)->field('o.*')->order($orderby)->select()->toArray();
        if (empty($lists)) $lists = [];
        foreach ($lists as $k => $order) {
            $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
            if (empty($goodslist)) $goodslist = [];
            foreach ($goodslist as $gk => $goods) {
                $goodslist[$gk]['stock'] = 0;
                if($status==2){
                    $stock = 0;
                    if ($goods['protype'] == 1) {
                        $stock = Db::name('shop_guige')->where('proid', $goods['proid'])->where('id', $goods['ggid'])->value('stock');
                    }
                    $goods_totalprice = round($goods['sell_price'] * $goods['num'],2);
                    $totalprice = $totalprice+$goods_totalprice;
                    $goodslist[$gk]['stock'] = $stock ?? 0;
                }
            }
            $lists[$k]['hangup_time'] = '';
            if ($order['hangup_time']) {
                $lists[$k]['hangup_time'] = date('Y-m-d H:i:s', $order['hangup_time']);
            }
            $lists[$k]['paytime'] = $order['paytime']?date('Y-m-d H:i:s', $order['paytime']):'';
            $lists[$k]['createtime'] = date('Y-m-d H:i:s', $order['createtime']);
            $lists[$k]['status_desc'] = $this->getOrderStatus($order['status']);
            if($order['mid']){
                $member =  Db::name('member')->where('id',$order['mid'])->field('id,nickname,realname')->find();
                $lists[$k]['buyer'] = $member['nickname']??'';
            }else{
                $lists[$k]['buyer'] = '匿名购买';
            }
            $lists[$k]['prolist'] = $goodslist ?? [];
        }
        return $this->json(1, 'ok', $lists);
    }

    public function getOrderDetail(){
        $orderid = input('param.orderid/d');
        $order = Db::name('cashier_order')->where('aid',aid)->where('bid',bid)->where('id', $orderid)->find();
        if(empty($order)){
            return $this->json(0,'该订单不存在');
        }
        $order['createtime'] = date("Y-m-d H:i:s",$order['createtime']);
        $order['paytime'] = $order['paytime']?date("Y-m-d H:i:s",$order['paytime']):'';
        $ordergoods = Db::name('cashier_order_goods')->where('orderid',$orderid)->select()->toArray();
        $order['prolist'] = $ordergoods??[];
        if($order['mid']){
            $member =  Db::name('member')->where('id',$order['mid'])->where('id,nickname,realname,')->find();
            $order['buyer'] = $member['nickname']??'';
        }else{
            $order['buyer'] = '匿名购买';
        }
        return $this->json(1, 'ok',$order);
    }

    /**
     * @description 删除订单
     */
    public function delCashierOrder()
    {
        $orderid = input('param.orderid/d', 0);
        $res = Db::name('cashier_order')->where('aid',aid)->where('bid',bid)->where('id', $orderid)->delete();
        if($res){
            $resg = Db::name('cashier_order_goods')->where('orderid', $orderid)->delete();
        }
        return $this->json(1, '删除成功');
    }

    /**
     * @description 收银台商品数量增减
     */
    public function cashierChangeNum()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $id = input('param.id', 0);
        $num = input('param.num/d', 0);
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '没有待结算订单不支持该操作');
        }
        $ordergoods = Db::name('cashier_order_goods')->where('orderid', $order['id'])->where('id', $id)->find();
        if (empty($ordergoods)) {
            return $this->json(0, '数据有误');
        }
        if ($num < 1) {
            //删除该商品
            Db::name('cashier_order_goods')->where('orderid', $order['id'])->where('id', $id)->delete();
        } else {
            Db::name('cashier_order_goods')->where('orderid', $order['id'])->where('id', $id)->update(['num' => $num]);
        }
        return $this->json(1, 'ok');
    }

    /**
     * @description 收银台商品数量增减
     */
    public function cashierChangePrice()
    {
        $cashier_id = input('param.cashier_id/d', 0);
        $id = input('param.id', 0);
        $price = input('param.price', 0);
        $order = $this->getWaitOrder($cashier_id);
        if (empty($order)) {
            return $this->json(0, '没有待结算订单不支持该操作');
        }
        Db::name('cashier_order_goods')->where('orderid', $order['id'])->where('id', $id)->update(['sell_price' => $price]);
        return $this->json(1, 'ok');
    }

    /**
     * 修改订单备注
     */
    public function cashierChangeRemark()
    {
        $orderid = input('param.orderid');
        $remark = input('param.remark');
        Db::name('cashier_order')->where('bid', bid)->where('aid', aid)->where('id', $orderid)->update(['remark' => $remark]);
        return $this->json(1, '备注修改成功');
    }

    /**
     * 修改订单状态
     */
    public function cashierChangeStatus()
    {
        $orderid = input('param.orderid');
        Db::name('cashier_order')->where('bid', bid)->where('aid', aid)->where('id', $orderid)->update(['status' => 1]);
        return $this->json(1, '修改成功');
    }


    /**
     * @description 获取用户信息
     */
    public function searchMember()
    {
        $keyword = input('param.keyword');
        if (empty($keyword)) {
            return $this->json(0, '请输入会员ID或手机号');
        }
        $member = Db::name('member')->where('aid',aid)->where('id|tel', $keyword)->field('id,nickname,realname,money,score,tel,createtime,birthday,remark,levelid')->find();
        if (empty($member)) {
            return $this->json(0, '未查到会员信息');
        }
        $member['couponcount'] = Db::name('coupon_record')->where('aid', aid)->where('bid',bid)->where('mid', $member['id'])
            ->where('status', 0)
            ->where('type','in',[1,2,10])
            ->where('starttime', '<=', time())->where('endtime', '>', time())->count();
        $mlevel = Db::name('member_level')->where('aid', aid)->where('id', $member['levelid'])->field('id,name,discount,icon')->find();
        $member['level_name'] = '';
        $member['level_icon'] = '';
        $member['tel'] = $member['tel'] ?? '';
        $member['birthday'] = $member['birthday'] ?? '';
        $member['realname'] = $member['realname'] ?? '';
        $member['level_discount'] = 0;
        $member['createtime'] = date('Y-m-d H:i:s', $member['createtime']);
        $address = Db::name('member_address')->where('mid', $member['id'])->field('id,name,tel,province,city,district,area,address')->order('isdefault desc')->find();
        $member['address'] = '';
        if ($address) {
            $member['address'] = ($address['province'] ?? '') . ($address['city'] ?? '') . ($address['district'] ?? '') . ($address['area'] ?? '') . ($address['address'] ?? '');
//            $member['address'] = $address;
        }
        if ($mlevel) {
            $member['level_name'] = $mlevel['name']??'';
            $member['level_icon'] = $mlevel['icon']??'';
            $member['level_discount'] = $mlevel['discount'];
        }
        return $this->json(1, 'ok', $member);
    }

    //会员优惠券
    public function memberCouponList()
    {
        $page = input('param.page/d', 1);
        $limit = input('param.limit/d', 10);
        $mid = input('param.mid/d', 0);
        $where = [];
        $where[] = ['aid', '=', aid];
        $where[] = ['bid', '=', bid];
        $where[] = ['mid', '=', $mid];
        $where[] = ['status', '=', 0];
        $where[] = ['type', 'in', [1,2,10]];
        $datalist = Db::name('coupon_record')->field('id,bid,type,limit_count,used_count,couponid,couponname,money,minprice,from_unixtime(starttime,"%Y-%m-%d %H:%i") starttime,from_unixtime(endtime,"%Y-%m-%d %H:%i") endtime,from_unixtime(usetime) usetime,from_unixtime(createtime) createtime,status')
            ->where($where)
            ->where('starttime', '<=', time())->where('endtime', '>', time())
            ->order('id desc')->page($page, $limit)->select()->toArray();
        if (!$datalist) $datalist = [];
        foreach ($datalist as $k => $v) {
            if ($v['bid'] > 0) {
                $binfo = Db::name('business')->where('aid', aid)->where('id', $v['bid'])->find();
                $datalist[$k]['bname'] = $binfo['name'];
            }
            $coupon = Db::name('coupon')->where('id', $v['couponid'])->field('isgive,fwtype')->find();
            $datalist[$k]['isgive'] = $coupon['isgive'];
            $datalist[$k]['fwtype'] = $coupon['fwtype'];
        }
        return $this->json(1, 'ok', $datalist);
    }


    //待收银订单status=0
    protected function getWaitOrder($cashier_id = 0)
    {
        $where = [];
        $where['status'] = 0;
        $where['aid'] = aid;
        $where['bid'] = bid;
        $where['cashier_id'] = $cashier_id;
        $order = Db::name('cashier_order')->where($where)->find();
        if (empty($order)) $order = [];
        return $order;
    }

    //打印小票
    public function print(){
        $orderid = input('post.orderid/d');
        //查找该商家是否有配置的打印机
        $machine = Db::name('wifiprint_set')->where('aid',aid)->where('bid',bid)->whereNotNull('client_id')->find();
        if(!$machine){
            return  $this->json(0,'未配置打印机');
        }
        $orderinfo  = Db::name('cashier_order')->where('aid',aid)->where('bid',bid)->where('id',$orderid)->find();
        if(empty($orderinfo)){
            return  $this->json(0,'订单信息有误');
        }
        \app\common\Wifiprint::print(aid,'cashier',$orderid);
        return $this->json(1,'打印成功');
    }



    protected function getOrderPrice($order=[],$couponrid=0,$userscore=0,$mid=0){
        //计算总价
        $goodslist = Db::name('cashier_order_goods')->where('orderid', $order['id'])->select()->toArray();
        if (empty($order) || empty($goodslist)) {
            return ['status'=>0,'msg'=>'暂无待结算订单'];
        }
        $totalprice = 0;
        foreach ($goodslist as $product) {
            if ($product['protype'] == 1) {
                $proids[] = $product['proid'];
            }
            //读取最新的价格
            $goods_totalprice = round($product['sell_price'] * $product['num'],2);
            if($goods_totalprice>0){
                Db::name('cashier_order_goods')->where('id',$product['id'])->update(['totalprice'=>$goods_totalprice]);
            }
            $totalprice = $totalprice + $goods_totalprice;
        }
        $pre_totalprice = $totalprice;
        $cidarr = [];
        if ($proids) {
            $cidarr = Db::name('shop_product')->where('bid', bid)->where('id', 'in', $proids)->column('cid','id');
        }
        //优惠券
        $coupon_money = 0;
        $scoredk_money = 0;
        $scoretotal = 0;
        $leveldk_money = 0;
        $moling_money = 0;
        //会员折扣
        if ($mid) {
            $member = Db::name('member')->where('id', $mid)->where('aid', aid)->find();
            $adminset = Db::name('admin_set')->where('aid', aid)->find();
            $userlevel = Db::name('member_level')->where('aid', aid)->where('id', $member['levelid'])->find();
            $level_discount = $userlevel['discount'];
            if (is_numeric($level_discount) && $level_discount<10) {
                $leveldk_money = round($totalprice * (10-$level_discount) * 0.1, 2);
                $totalprice = $totalprice - $leveldk_money;
            }
            //积分抵扣
            if($userscore && $adminset['score2money']>0){
                if($adminset['scoredkmaxpercent']>0 && $adminset['scoredkmaxpercent']<=100){
                    $scoreMaxDk = round($totalprice * $adminset['scoredkmaxpercent']*0.01,2);
                }else{
                    $scoreMaxDk = $totalprice;
                }
                $scoredk_money = round($member['score'] * $adminset['score2money'], 2);
                $scoredk_money = min($scoreMaxDk,$scoredk_money);
                $scoretotal = intval($scoredk_money / $adminset['score2money'] * 10);
            }
            $totalprice = $totalprice-$scoredk_money;

            if ($couponrid) {
                $couponrecord = Db::name('coupon_record')->where("bid=-1 or bid=" . bid)->where('aid', aid)->where('mid', $mid)->where('id', $couponrid)->find();
                if (!$couponrecord) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '不存在'];
                } elseif ($couponrecord['status'] != 0) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '已使用过了'];
                } elseif ($couponrecord['starttime'] > time()) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '尚未开始使用'];
                } elseif ($couponrecord['endtime'] < time()) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '已过期'];
                } elseif ($couponrecord['minprice'] > $totalprice) {
                    return ['status'=>0,'msg'=>'该' .'该' . t('优惠券') . '不符合条件'];
                } elseif ($couponrecord['type'] != 1 && $couponrecord['type'] != 4) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '不符合条件'];
                }

                $couponinfo = Db::name('coupon')->where('aid', aid)->where('id', $couponrecord['couponid'])->find();
                if (empty($couponinfo)) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '不存在或已作废'];
                }
                //0全场通用,1指定类目,2指定商品
                if (!in_array($couponinfo['fwtype'], [0, 1, 2])) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '超出可用范围'];
                }
                if ($couponrecord['from_mid']==0 && $couponinfo && $couponinfo['isgive'] == 2) {
                    return ['status'=>0,'msg'=>'该' . t('优惠券') . '仅可转赠'];
                }
                if ($couponinfo['fwtype'] == 2) {//指定商品可用
                    $productids = explode(',', $couponinfo['productids']);
                    if (!array_intersect($proids, $productids)) {
                        return ['status'=>0,'msg'=>'该' . t('优惠券') . '指定商品可用'];
                    }
                    $thistotalprice = 0;
                    foreach ($goodslist as $k2 => $product) {
                        if (in_array($product['proid'],$productids)){
                            $thistotalprice += $product['sell_price'] * $product['num'];
                        }
                    }
                    if ($thistotalprice < $couponinfo['minprice']) {
                        return ['status'=>0,'msg'=>'该' . t('优惠券') . '指定商品未达到' . $couponinfo['minprice'] . '元'];
                    }
                }
                if ($couponinfo['fwtype'] == 1) {//指定类目可用
                    $categoryids = explode(',', $couponinfo['categoryids']);
                    $categoryids1 = Db::name('shop_category')->where('pid', 'in', $categoryids)->select()->toArray();
                    if (empty($categoryids1)) $categoryids1 = [];
                    $categoryids = array_merge($categoryids, $categoryids1);
                    $cids = array_values($cidarr);
                    if (!array_intersect($cids, $categoryids)) {
                        return ['status'=>0,'msg'=>'该' . t('优惠券') . '指定分类可用'];
                    }
                    $thistotalprice = 0;
                    foreach ($goodslist as $k2 => $product) {
                        if(isset($cidarr[$product['proid']])){
                            $thistotalprice += $product['sell_price'] * $product['num'];
                        }
                    }
                    if ($thistotalprice < $couponinfo['minprice']) {
                        return ['status'=>0,'msg'=>'该' . t('优惠券') . '指定分类未达到' . $couponinfo['minprice'] . '元'];
                    }
                    $coupon_money += $couponrecord['money'];
                }else{
                    $coupon_money += $couponrecord['money'];
                }
                if ($coupon_money > $totalprice) $coupon_money = $totalprice;
                $totalprice =  round($totalprice - $coupon_money, 2);
            }
        }
        //抹零
        if($order['remove_zero']){
            $zeroinfo = $this->removeZero($totalprice,$order['cashier_id']);
            $moling_money = $zeroinfo['moling_money']??0;
            $totalprice = $totalprice - $moling_money;
        }
        return [
            'status'=>1,
            'pre_totalprice' =>$pre_totalprice,
            'totalprice' =>$totalprice,
            'moling_money'=>$moling_money,
            'coupon_money'=>$coupon_money,
            'leveldk_money'=>$leveldk_money,
            'scoredk_money'=>$scoredk_money,
            'totalscore' => $scoretotal
        ];
    }

    public function getOrderStatus($status){
        $arr =[0=>'待付款',1=>'已支付',2=>'挂单',3=>'st3',4=>'已关闭'];
        return $arr[$status]??$status;
    }

    //格式化返回
    protected function json($status = 0, $msg = '', $data = '')
    {
        return json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

}
